{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(4.9630)\n",
      "tensor(4.9630)\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import sys\n",
    "sys.path.append(\"..\") \n",
    "#功能： 计算output和target之差的绝对值，\n",
    "# L1 L0ss\n",
    "def my_mes(y, y_hat):\n",
    "    return ((y-y_hat)**2).mean()\n",
    "\n",
    "\n",
    "y = torch.tensor([1.143,6.6,1.345,5])\n",
    "y_hat = torch.tensor([1.1,3.1,4.1,5.1])\n",
    "MSE_loss = nn.MSELoss()\n",
    "\n",
    "print(MSE_loss(y,y_hat))\n",
    "print(my_mes(y, y_hat))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(1.5995)\n",
      "tensor(1.5995)\n"
     ]
    }
   ],
   "source": [
    "# MSELoss 平方loss \n",
    "\n",
    "def my_L1loss(y, y_hat):\n",
    "      return (torch.abs((y-y_hat))).mean()\n",
    "    \n",
    "    \n",
    "L1_loss = nn.L1Loss()\n",
    "\n",
    "\n",
    "print(L1_loss(y,y_hat))\n",
    "      \n",
    "print(my_L1loss(y,y_hat)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(1.7661)\n",
      "tensor(1.7661)\n"
     ]
    }
   ],
   "source": [
    "#交叉熵LOSS\n",
    "\n",
    "def my_CEL(y, y_label):\n",
    "    total_loss = torch.zeros(y.shape[0])\n",
    "    for i, class_index in enumerate(y_label):\n",
    "        x_j =  torch.cat((y[i,0:class_index], y[i, class_index+1:]))\n",
    "        total_loss[i] = -y[i,class_index] + torch.log( torch.exp(y[i]).sum())\n",
    "        \n",
    "    return total_loss.mean()\n",
    "\n",
    "cel_loss =nn.CrossEntropyLoss()\n",
    "\n",
    "y = torch.tensor([[ 0.0606, -1.1610, -1.2990, 0.2101, 1.5104], [-0.6388, -0.4053, -0.4196, 0.7060, 2.2793], [ 0.3973, 0.6114, -0.1127, -0.7732, -0.0592]])\n",
    "y_label = torch.tensor([4,1,4])\n",
    "\n",
    "print(cel_loss(y, y_label))\n",
    "\n",
    "print(my_CEL(y,y_label))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
